/*
* 1.新增报表权限（不包括自定义适用人员）
* 2.编辑报表权限（不包括自定义适用人员）
* 3.显示默认值
* */

import React from "react";
import { connect } from 'react-redux';
import { Button, Form, Input, Switch, Icon, Select, message } from 'antd';
import SelectDepWithChildren from "components/template/select-depment-with-children/select-depment-with-children";
import ReportDistributionService from "containers/data-center/report-distribution/report-distribution.service";
import { deepFullCopy, messages } from "share/common";
import "styles/data-center/report-distribution/edit-report-permission.scss";
import Chooser from "components/chooser";
import {
  grantArr,
  APP_REPORT_ARRAY,
  WEB_PERSONAL_REPORT_ID,
  GRANT_FILTER,
  DATA_AREA_FILTER
} from "containers/data-center/report-distribution/report-permission.model";
import LanguageInput from 'components/template/language-input/language-input'
import SelectAllCostCenterItem from 'components/template/select-all-cost-center-item/select-all-cost-center-item.js';


const FormItem = Form.Item;
const Option = Select.Option;

class ReportDistributionMaintain extends React.Component {
  constructor(props) {
    super(props);
    let tempArray = this.getFilterGrantArr(props.params.reportId, grantArr);
    this.state = {
      loading: false,
      reportDetail: {},//报表详情
      reportDetailBackUp: {},//报表详情，取消时备用
      dataAreaOptions: [],//数据范围
      grantArr: tempArray,
      costCenter: [],//成本中心项
      copyReportCorporation: [],//法人实体
      checkedSetOfBookList: [],//账套
      checkedDep: [],//包含下级部门
      checkedParDep: [],//不包含下级部门
      checkedCompany: [],//公司
    };
  }

  componentWillReceiveProps(nextProps) {
    const params = nextProps.params;
    // props每变一次就会调用一次，所以赋值如果写一起会被空值覆盖
    if (!params || params === this.props.params) {
      return false;
    } else {
      //先做新增
      let { reportDetail, reportId, dataAreaOptions } = params;
      //深度拷贝，点击取消用
      let reportDetailBackUp = deepFullCopy(reportDetail);
      let tempArray = this.getFilterDataAreaOptions(reportId, dataAreaOptions);
      this.setState({
        reportDetail,
        reportDetailBackUp,
        dataAreaOptions: tempArray,
        copyReportCorporation: [],
        checkedSetOfBookList: [],
        checkedDep: [],
        costCenter: [],
        checkedParDep: [],
        checkedCompany: [],
      }, () => {
        let res = this.setDefaultArrDataArea(reportDetail.permission);
        this.setState({
          checkedSetOfBookList: res.checkedSetOfBookList,
          copyReportCorporation: res.copyReportCorporation,
          checkedCompany: res.checkedCompany,
          checkedParDep: res.checkedParDep,
          checkedDep: res.checkedDep,
          costCenter: res.costCenter
        })
      });
    }
  }

  getFilterGrantArr = (reportId, grantArr) => {
    reportId = Number(reportId);
    return APP_REPORT_ARRAY.includes(reportId) ? grantArr.filter(item => {
      return GRANT_FILTER[reportId][item.value]
    }) : grantArr
  };

  getFilterDataAreaOptions = (reportId, dataAreaOptions) => {
    reportId = Number(reportId);
    return APP_REPORT_ARRAY.includes(reportId) || reportId === WEB_PERSONAL_REPORT_ID ? dataAreaOptions.filter(item => {
      return DATA_AREA_FILTER[reportId][item.permission_prop]
    }) : dataAreaOptions.filter(item => {
      return !DATA_AREA_FILTER["normal"][item.permission_prop]
    });
  };

  setDefaultArrDataArea = (permissionArr) => {
    let res = {
      checkedSetOfBookList: [],
      copyReportCorporation: [],
      checkedCompany: [],
      checkedParDep: [],
      checkedDep: [],
      costCenter: [],
    }
    if (permissionArr && permissionArr.length) {
      permissionArr.map(item => {
        let obj = this.setDefaultDataArea(item);
        obj.key && res[obj.key].push(obj.value);
      })
    }
    return res
  }
  //设置默认权限范围
  setDefaultDataArea = (item) => {
    let obj = {
      key: null,
      value: null
    };
    let type = item.permissionProp;
    switch (type) {
      case "sob": {
        item.setOfBooksId = item.permissionValue;
        item.setOfBooksName = item.permissionDesc;
        obj = {
          key: "checkedSetOfBookList",
        }
        break;
      }
      case "le": {
        item.key = item.permissionValue;
        item.companyName = item.permissionDesc;
        obj = {
          key: "copyReportCorporation",
        }
        break;
      }
      case "company": {
        item.companyOID = item.permissionValue;
        item.name = item.permissionDesc;
        obj = {
          key: "checkedCompany",
        }
        break;
      }
      case "dept": {
        item.key = item.permissionValue;
        item.name = item.permissionDesc;
        item.label = item.permissionDesc;
        obj = {
          key: "checkedParDep",
        }
        break;
      }
      case "dept_full": {
        item.key = item.permissionValue;
        item.name = item.permissionDesc;
        item.label = item.permissionDesc;
        obj = {
          key: "checkedDep",
        }
        break;
      }
      case "costitem": {
        item.costCenterItemOID = item.permissionValue;
        item.name = item.permissionDesc;
        obj = {
          key: "costCenter",
        }
        break;
      }
    }
    if (obj.key) {
      obj.value = item;
    }
    return obj;
  }

  //通过用户选择的值，得到要上传的数据结构
  setPermissionFiledByValue = (val) => {
    let reportDetail = this.state.reportDetail;
    let grant = getNameByValue(val, this.state.dataAreaOptions);
    const onlyPropValue = ['all', 'userle', 'usercom', 'user_dept', 'user_dept_full', 'applicant',
      'user_mng_dept', 'user_mng_dept_full', 'user_mng_cci'];  // 别问我，我也不知道这是啥意思
    if (onlyPropValue.includes(grant.value)) {
      // 仅仅有属性
      return [
        {
          //只是修改的时候传id，新增的时候不要id
          "id": reportDetail.permission && reportDetail.permission.length && reportDetail.permission.length > 0 ? reportDetail.permission[0].id : undefined,
          "permissionProp": grant.value,
        }
      ];
    } else {
      // 属性 值
      // sob sobid
      // le leoid
      // company companyoid
      // dept deptcode
      // dept_full deptcode
      // costitem itemoid
      //这种是需要被单独处理
      const {
        checkedSetOfBookList,
        copyReportCorporation,
        checkedCompany,
        checkedParDep,
        checkedDep,
        costCenter,
      } = this.state;
      let arr = [];
      switch (val) {
        case "sob": {
          arr = checkedSetOfBookList;
          arr = arr.map(item => {
            let obj = {};
            //只是修改的时候传id，新增的时候不要id
            // obj.id =  reportDetail.permission[0].id ;
            obj.permissionProp = val;
            obj.permissionValue = item.setOfBooksId;
            return obj;
          });
          break;
        }
        case "le": {
          arr = copyReportCorporation;
          arr = arr.map(item => {
            let obj = {};
            //只是修改的时候传id，新增的时候不要id
            // obj.id =  reportDetail.permission[0].id ;
            obj.permissionProp = val;
            obj.permissionValue = item.companyReceiptedOID;
            return obj;
          });
          break;
        }
        case "company": {
          arr = checkedCompany;
          arr = arr.map(item => {
            let obj = {};
            //只是修改的时候传id，新增的时候不要id
            // obj.id =  reportDetail.permission[0].id ;
            obj.permissionProp = val;
            obj.permissionValue = item.companyOID;
            return obj;
          });
          break;
        }
        case "dept": {
          arr = checkedParDep;
          arr = arr.map(item => {
            let obj = {};
            //只是修改的时候传id，新增的时候不要id
            // obj.id =  reportDetail.permission[0].id ;
            obj.permissionProp = val;
            obj.permissionValue = item.key;
            return obj;
          });
          break;
        }
        case "dept_full": {
          arr = checkedDep;
          arr = arr.map(item => {
            let obj = {};
            //只是修改的时候传id，新增的时候不要id
            // obj.id =  reportDetail.permission[0].id ;
            obj.permissionProp = val;
            obj.permissionValue = item.key;
            return obj;
          });
          break;
        }
        case "costitem": {
          arr = costCenter;
          //选择成本中心项
          arr = arr.map(item => {
            let obj = {};
            //只是修改的时候传id，新增的时候不要id
            // obj.id =  reportDetail.permission[0].id ;
            obj.permissionProp = val;
            obj.permissionValue = item.costCenterItemOID;
            return obj;
          });
          break;
        }
      }
      if (arr.length > 0) {
        return arr
      } else {
        message.warning(messages('data-center.key43')/*请选择数据范围值*/);
        return false;
      }
    }

    function getNameByValue(grantProp, permissionCodesArr) {
      let t = {
        name: undefined,
        value: undefined
      };
      permissionCodesArr.map(item => {
        if (grantProp === item.permission_prop) {
          t.name = item.permission_desc;
          t.value = item.permission_prop;
        }
      });
      return t;
    }
  }

  //通过用户选择的值，得到要上传的数据结构
  setGrantFiledByValue = (val) => {
    let reportDetail = this.state.reportDetail;
    if (val === "userGroup") {
      return [
        {
          "grantProp": "userGroup",// 固定值
          "grantValue": "",// 固定值
          "grantDesc": messages('data-center.key113')/*指定人员组*/// 固定值
        }
      ];
    }
    if (val === "user") {
      return [];
    }
    let grant = getNameByValue(val, grantArr);
    let obj = {
      //修改需要传id
      "id": reportDetail.grant && reportDetail.grant.length && reportDetail.grant.length > 0 ? reportDetail.grant[0].id : undefined,
      "grantProp": grant.value,
      "grantValue": grant.value,
      "grantDesc": grant.name
    }
    return [obj];

    function getNameByValue(grantProp, grantArr) {
      let t = {
        name: undefined,
        value: undefined
      };
      grantArr.map(item => {
        if (grantProp === item.value) {
          t.name = item.name;
          t.value = item.value;
        }
      });
      return t;
    }
  }

  setPermissionArrFiledByValue = (permissionArr) => {
    let res = [];
    if (permissionArr && permissionArr.length) {
      permissionArr.map(item => {
        res = res.concat(this.setPermissionFiledByValue(item));
      })
    }
    if (checkPermissionIsEmpty(res)) {
      return false;
    } else {
      return res;
    }

    function checkPermissionIsEmpty(res) {
      for (let i = 0; i < res.length; i++) {
        if (res[i] === false) {
          return true
        }
      }
    }
  }
  //更新
  saveReportAction = (e) => {
    e.preventDefault();
    let reportDetail = this.state.reportDetail;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let _permission = this.setPermissionArrFiledByValue(values.permission);
        if (_permission) {
          values.permission = _permission;
          values.grant = this.setGrantFiledByValue(values.grant);
          values.sourceReportId = reportDetail.sourceReportId;
          values.tenantId = reportDetail.tenantId;
          values.i18n = reportDetail.i18n;
          if (reportDetail.id) {
            //编辑
            values.id = reportDetail.id;
          }
          this.updateReportPermission(values)
        }
      }
    })
  }
  // 新增或者更新
  updateReportPermission = (reportPermission) => {
    this.setState({
      loading: true
    });
    let reportDetail = this.state.reportDetail;
    ReportDistributionService.updateReportPermission(reportPermission)
      .then((response) => {
        //for clear cache
        reportDetail.remark = "";
        reportDetail.i18n = null;
        this.setState({
          loading: false,
          reportDetail
        });
        this.props.form.resetFields();
        this.props.close(true);
        message.success(messages('common.operate.success'));
      })
      .catch(() => {
        this.setState({
          loading: false
        });
      });
  };

  onCancel = () => {
    this.props.form.resetFields();
    this.setState({
      reportDetail: {},
      copyReportCorporation: [],
      checkedSetOfBookList: [],
      checkedDep: [],
      costCenter: [],
      checkedParDep: [],
    });
    this.props.close();
  };

  //添加部门 包括下级
  addDepCallback = (result) => {
    this.setState({
      checkedDep: result
    });
  };

  //添加部门，不包括下级
  addParDepCallback = (result) => {
    this.setState({
      checkedParDep: result
    });
  }
  //添加法人实体
  getCorporation = (result) => {
    this.setState({
      copyReportCorporation: result
    });
  }
  //添加账套
  getSetOfBookList = (result) => {
    this.setState({
      checkedSetOfBookList: result
    });
  }
  //添加公司
  getCompanyList = (result) => {
    this.setState({
      checkedCompany: result
    });
  }
  //添加成本中心
  getCostCenter = (result) => {
    this.setState({
      costCenter: result
    });
  }
  onClearCostCenter = (result) => {
    //result是空数组
    this.setState({
      costCenter: result
    });
  }

  handleClose = (removedTag) => {
    const checkedDep = this.state.checkedDep.filter(tag => tag.departmentOID !== removedTag);
    this.setState({ checkedDep });
  };

  //状态
  handleEnableChange = (e) => {
    let reportDetail = this.state.reportDetail;
    reportDetail.enable = e;
    this.setState({
      reportDetail
    })
  }
  //获取权限范围细项
  getPermissionItem = (type) => {
    let {
      checkedDep,
      checkedParDep,
      copyReportCorporation,
      checkedSetOfBookList,
      checkedCompany,
      costCenter
    } = this.state;
    switch (type) {
      case "dept_full": //指定部门 包括下级部门
      {
        return (
          <div className='position-wrap'>
            <div>{messages('data-center.key117')/*指定部门包括下级部门*/}</div>
            <SelectDepWithChildren onConfirm={this.addDepCallback}
                                   isIncludeChildren={true}
                                   title={messages('report-distribution.key19'/*指定部门（包含下级部门）*/)}
                                   defaultValue={checkedDep}
            />
          </div>
        );
        break;
      }
      case "dept": //指定部门 不包括下级部门
      {
        return (
          <div className='position-wrap'>
            <div>{messages('data-center.key118')/*指定部门不包括下级部门*/}</div>
            <SelectDepWithChildren onConfirm={this.addParDepCallback}
                                   isIncludeChildren={false}
                                   title={messages('report-distribution.key20'/*指定部门（不包含下级部门）*/)}
                                   defaultValue={checkedParDep}
            />
          </div>

        );
        break;
      }
      case "le": //指定法人
      {
        return (
          <div className={"le"} key={"le"}>
            <div>{messages('data-center.key119')/*指定法人*/}</div>
            <Chooser type={"corporation_entity_all"}
                     valueKey={"key"}
                     labelKey={"companyName"}
                     newline={true}
                     value={copyReportCorporation}
                     onChange={this.getCorporation}
            />
          </div>
        );
        break;
      }
      case "sob": //指定账套
      {
        return (
          <div className={"sob"} key={"sob"}>
            <div>{messages('data-center.key120')/*指定账套*/}</div>
            <Chooser type={"select_set_of_books"}
                     valueKey={"setOfBooksId"}
                     newline={true}
                     labelKey={"setOfBooksName"}
                     value={checkedSetOfBookList}
                     onChange={this.getSetOfBookList}
            />
          </div>
        );
        break;
      }
      case "company": //指定公司
      {
        return (
          <div>
            <div>{messages('data-center.key121')/*指定公司*/}</div>
            <Chooser type={"enabled_company"}
                     newline={true}
                     valueKey={"companyOID"}
                     labelKey={"name"}
                     value={checkedCompany}
                     onChange={this.getCompanyList}
            />
          </div>
        );
        break;
      }
      case "costitem": //指定成本中心项
      {
        //选择整个租户下的成本中心
        return (
          <div>
            <div>{messages('data-center.key122')/*指定成本中心项*/}</div>
            <SelectAllCostCenterItem
              onClear={this.onClearCostCenter}
              originSelectedData={costCenter}
              onConfirm={this.getCostCenter}
            />
          </div>
        );
        break;
      }
    }
  }
  //渲染权限范围
  renderDataArea = () => {
    let daValue = this.props.form.getFieldValue('permission');
    return daValue && daValue.map && daValue.map(item => {
      return this.getPermissionItem(item)
    })
  };

  handleRemarkChange = (value, i18n) => {
    const { reportDetail } = this.state;
    reportDetail.remark = value;
    if (!reportDetail.i18n) {
      reportDetail.i18n = {};
    }
    reportDetail.i18n.remark = i18n;
  }

  render() {
    const { reportDetail, dataAreaOptions, grantArr } = this.state;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 6, offset: 1 },
      wrapperCol: { span: 14, offset: 1 }
    };
    return (
      <Form onSubmit={this.saveReportAction}
            className="edit-report-distribution-permission-wrap">
        <FormItem
          {...formItemLayout}
          label={messages('data-center.key32')/*报表*/}
        >
          {getFieldDecorator('reportName', {
            initialValue: reportDetail.reportName,
            rules:
              [{
                required: true,
                message: messages("common.please.enter")
              }],
          })(
            <Input value={reportDetail.reportName} disabled={true}/>
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label={messages('report-distribution.key25'/*说明*/)}
        >
          {getFieldDecorator('remark', {
            initialValue: reportDetail.remark,
          })(
            <LanguageInput key={reportDetail.id}
                           name={reportDetail.remark || null}
                           i18nName={reportDetail.i18n && reportDetail.i18n.remark}
                           isEdit={reportDetail.id}
                           nameChange={this.handleRemarkChange}
            />
          )}
        </FormItem>
        <FormItem
          {...formItemLayout}
          label={messages("common.column.status")}
        >
          {getFieldDecorator('enable', {
            initialValue: reportDetail.enable,
            rules:
              [{
                required: true,
                message: messages("common.please.enter")
              }],
          })(
            <Switch checkedChildren={<Icon type="check"/>}
                    unCheckedChildren={<Icon type="cross"/>}
                    checked={reportDetail.enable}
                    onChange={this.handleEnableChange}
            />
          )}
          <span className={"report-distribution-switch-span"}>
          {reportDetail.enable ? messages('report-distribution.key10'/*启用*/) : messages('report-distribution.key11'/*未启用*/)}
          </span>
        </FormItem>


        <FormItem
          {...formItemLayout}
          label={messages('report-distribution.key28'/*报表可见人员*/)}
        >
          {getFieldDecorator('grant', {
            initialValue: reportDetail._grant,
            rules:
              [{
                required: true,
                message: messages("common.please.enter")
              }],
          })(
            <Select placeholder={messages('common.please.select')}>
              {grantArr.map(option => {
                return <Option key={option.id}
                               value={option.value}>
                  {option.name}
                </Option>
              })}
            </Select>
          )}
        </FormItem>


        <FormItem
          {...formItemLayout}
          label={messages('report-distribution.key27'/*可见数据范围*/)}
        >
          {getFieldDecorator('permission', {
            initialValue: reportDetail._permission,
            rules: [{
              required: true,
              message: messages("common.please.enter")
            }],
          })(
            <Select mode="multiple" placeholder={messages('common.please.select')}>
              {dataAreaOptions.map(option => {
                return <Option key={option.id}
                               value={option.permission_prop}>
                  {option.permission_desc}
                </Option>
              })}
            </Select>
          )}
          {this.renderDataArea()}
        </FormItem>


        {/*//所在分配人员列表*/}
        <div className="slide-footer">
          <Button type="primary"
                  htmlType="submit"
                  loading={this.state.loading}>
            {messages("common.save")}
          </Button>
          &nbsp;&nbsp;&nbsp;
          <Button onClick={this.onCancel}>
            {messages("common.cancel")}
          </Button>
        </div>
      </Form>
    );
  }
}

function mapStateToProps(state) {
  return {
    language: state.login.user.language,
    user: state.login.user,
  }
}

const ReportDistributionMaintainForm = Form.create()(ReportDistributionMaintain);
export default connect(mapStateToProps)(ReportDistributionMaintainForm);


